
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */
var insertIntoBST = function(root, val) {
  if(!root) {
    return new TreeNode(val);
  }
  function insertNode(node) {
    if(node.val > val) {
      if(node.left) {
        insertNode(node.left);
      } else {
        let tempNode = new TreeNode(val);
        node.left = tempNode;
      }
    } else {
      if(node.right) {
        insertNode(node.right);
      } else {
        let tempNode = new TreeNode(val);
        node.right = tempNode;
      }
    }
    return;
  }
  insertNode(root);
  return root;
};
